# -*- coding: utf-8 -*-
#----------------------------------------------
# @note: Запуск зависимого проекта/билда
# @author: Andrey Simine/Андрей Симин
# @copyright: (C) 2023
#----------------------------------------------

from chainlib.basic_link import BasicLink

from pprint import pprint
import requests
import json

__author__ = 'asimine'

class UserLink(BasicLink):

    def __init__(self, context):
        super(UserLink, self).__init__(context)

    def execute(self):
        print("Input context: ")
        pprint(self.context)

        print("Parameters: ")
        pprint(self.parameters) 
        build_url = f"http://{self.parameters['host']}:{self.parameters['port']}/api/1.0/build/create/{self.parameters['project_id']}"        
        print(f"URL: {build_url}")

        # set parent host data for callback         
        _parent_host = "Undefined"
        _parent_port = "Undefined"
        _chain_data_context = self.context["chain_data"]["context"]
        if "global_variables" in _chain_data_context:
            _parent_host = _chain_data_context["global_variables"]["CAROUSEL_HOSTNAME"]   
            _parent_port = _chain_data_context["global_variables"]["CAROUSEL_HOSTPORT"]

        upstairs_dependencies = {"safe": {
                                    "dependencies": {
                                       "upstairs": [
                                          {"host": _parent_host,
                                           "port": _parent_port,
                                           "build_id": self.context['chain_data']['build_id']}
                                          ]
                                    }
                                 }}
        print(f"upstairs_dependencies:")
        pprint(upstairs_dependencies)

        r = requests.put(build_url, 
                         data=json.dumps(upstairs_dependencies),
                         headers={'Content-type': 'application/json', 'Accept': 'text/plain'})
        r.raise_for_status()

        json_result = r.json()
        pprint(json_result)
        print(f"Build for project {self.parameters['project_id']} was successfully started: {json_result['result']['_id']}")
        
        print("Saving dependenciy data...")
        safe_context = {"safe": {
                            "dependencies": {
                                "downstairs": [
                                 {"host": self.parameters['host'],
                                  "port": self.parameters['port'],
                                  "build_id": json_result['result']['_id']}  
                                ]
                            }
                        }
                       } 
        self.update_context(safe_context)
       
        print("Finish dependencies tracking.")     
        
        
        
         
